/* eslint-disable prefer-promise-reject-errors */
import axios from 'axios'
import { getToken } from '../utils/auth'
import qs from 'qs'
import { ElMessage } from 'element-plus'

const service = axios.create({
  timeout: 5000
})

service.interceptors.request.use(
  config => {
    // 设置请求头
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    config.transformRequest = [
      function (data) {
      // 在请求之前对data传参进行格式转换
        data = qs.stringify(data)
        return data
      }
    ]
    // 判断是否存在token，如果存在的话，则每个http header都加上token
    const token = getToken()
    if (token) {
      config.headers.token = getToken()
    }
    return config
  },
  error => {
    ElMessage.error(error)
    return Promise.reject()
  }
)

service.interceptors.response.use(
  response => {
    if (response.status === 200) {
      return response.data
    } else {
      Promise.reject()
    }
  },
  () => {
    ElMessage.error('网络请求异常，请稍后再试！')
    return Promise.reject()
  }
)

export default service
